package ru.st.selenium;


import java.awt.Toolkit;
//import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
//import java.awt.datatransfer.Transferable;
//import java.util.regex.Pattern;
//import java.util.concurrent.TimeUnit;
//
//import javafx.scene.input.Clipboard;
//import javafx.scene.input.ClipboardContent;

import java.util.concurrent.TimeUnit;

import org.testng.*;
import org.testng.annotations.*;
import org.openqa.selenium.*;

import com.sun.corba.se.impl.orbutil.threadpool.TimeoutException;

public class FindFilm extends ru.st.selenium.pages.TestBase {
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();
  // Login params
  String login = "admin";
  String pass = "admin";
  // Film params
  String simple_title = "Original name";
  String wrong_title = "Origenal name";
  String simple_year = "2033";
  String wrong_year = "2053";
  
  @Test // Find film 
  public void testFindFilm() throws TimeoutException, InterruptedException {
	driver.get(baseUrl + "/php4dvd/");
	findAndWrite(By.id("username"), login);
	findAndWrite(By.name("password"), pass);
	driver.findElement(By.name("submit")).click();
	// Checking films with the same name
	waitForElementPresent(By.className("searchbox"));
	String searchPath = "//div[@class='searchbox']/input[@type='text']";
	findAndWrite(By.xpath(searchPath), simple_title);
	driver.findElement(By.xpath(searchPath)).sendKeys(Keys.ENTER);
	Thread.sleep(1000);
	driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
	int resultSizeFirst= driver.findElement(By.id("results")).findElements(By.tagName("a")).size();
	driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	// Adding film with original name
	waitForElementPresent(By.cssSelector("img[alt=\"Add movie\"]"));
	driver.findElement(By.cssSelector("img[alt=\"Add movie\"]")).click();
	waitForElementPresent(By.name("name"));
	findAndWrite(By.name("name"), simple_title);
	findAndWrite(By.name("year"), simple_year);
	driver.findElement(By.name("submit")).click();
	waitForElementPresent(By.className("maininfo_full"));
	driver.get(baseUrl + "/php4dvd/");
	// Search
	waitForElementPresent(By.className("searchbox"));
	// Search wrong title
	findAndWrite(By.xpath(searchPath), wrong_title);
	driver.findElement(By.xpath(searchPath)).sendKeys(Keys.ENTER);
	Thread.sleep(1000);
	// Expected no results
	driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
	int resultSize1 = driver.findElement(By.id("results")).findElements(By.tagName("a")).size();
	driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	Assert.assertTrue(resultSize1 == 0);
	// Search wrong year
	findAndWrite(By.xpath(searchPath), wrong_year);
	driver.findElement(By.xpath(searchPath)).sendKeys(Keys.ENTER);
	Thread.sleep(1000);
	// Expected no results
	driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
	int resultSize2 = driver.findElement(By.id("results")).findElements(By.tagName("a")).size();
	driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	Assert.assertTrue(resultSize2 == 0);
	// Search true title
	findAndWrite(By.xpath(searchPath), simple_title);
	driver.findElement(By.xpath(searchPath)).sendKeys(Keys.ENTER);
	Thread.sleep(1000);
	// Expected 1 result
	driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
	int resultSize3 = driver.findElement(By.id("results")).findElements(By.tagName("a")).size();
	driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	Assert.assertTrue(resultSize3 - resultSizeFirst == 1);
	// Search true year
	findAndWrite(By.xpath(searchPath), simple_year);
	driver.findElement(By.xpath(searchPath)).sendKeys(Keys.ENTER);
	Thread.sleep(1000);
	// Expected 1 result
	driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
	int resultSize4 = driver.findElement(By.id("results")).findElements(By.tagName("a")).size();
	driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	Assert.assertTrue(resultSize4 - resultSizeFirst == 1);
	// Select result and check title and year
	driver.findElement(By.id("results")).findElement(By.tagName("a")).click();
	String fullInfo = driver.findElement(By.className("maininfo_full")).getText();
	Assert.assertTrue(fullInfo.contains(simple_title));
	Assert.assertTrue(fullInfo.contains(simple_year));
	// Delete result
	driver.findElement(By.id("content")).findElement(By.xpath("//img[@alt='Remove']")).click();
	closeAlertAndGetItsText();
	// Check successful removing
	findAndWrite(By.xpath(searchPath), simple_title);
	driver.findElement(By.xpath(searchPath)).sendKeys(Keys.ENTER);
	Thread.sleep(1000);
	driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
	int resultSizeLast = driver.findElement(By.id("results")).findElements(By.tagName("a")).size();
	driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	Assert.assertTrue(resultSizeLast - resultSizeFirst == 0);
	logout();
  }
  
  
  private void logout() {
	  driver.findElement(By.xpath("//*[@id='wrapper']/header/div/nav/ul/li[4]/a")).click();
		closeAlertAndGetItsText();
	  }
  
  private void waitForElementPresent(By by) throws TimeoutException, InterruptedException {
	for (int count = 0;; count ++) {
		if (count >= 30)
			throw new TimeoutException();
		try {
			driver.findElement(by);
			break;
		} catch (NoSuchElementException e) {}
		Thread.sleep(1000);
	}
  }

  private void findAndWrite(By by, String text) throws InterruptedException {
	WebElement element = driver.findElement(by);
	trueClear(element);
	element.sendKeys(text);
  }
  
  private void findAndPaste(By by, String text) throws InterruptedException {
		WebElement element = driver.findElement(by);
		trueClear(element);
		setClipboardContents(text);
		element.sendKeys(Keys.COMMAND + "v");
	  }
  
  private void setClipboardContents(String string) {
      StringSelection stringSelection = new StringSelection(string);
      Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
              stringSelection, null);
  }
  
  private void trueClear(WebElement element) throws InterruptedException {
	element.sendKeys(Keys.COMMAND + "a");
	Thread.sleep(200);
	element.sendKeys(Keys.DELETE);
  }
  
  private boolean isElementPresent(By by) {
    return driver.findElements(by).size() > 0;
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}
